package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.ParameterIsNullException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.param.EemInsertParam;
import com.sky.pojo.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.EmployeeService;
import com.sky.utils.GetOperatorId;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    EmployeeMapper employeeMapper;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    GetOperatorId getOperatorId;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Result<EmployeeLoginVO> login(EmployeeLoginDTO employeeLoginDTO) {
        //一、校验参数
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new ParameterIsNullException("用户名或密码不能为空");
            //return Result.error("用户名或密码不能为空");
        }

        //二、处理业务
        //1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        //  后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
//        在使用equals对比时，应该讲常量写在前面，防止空指针异常
        if (StatusConstant.DISABLE.equals(employee.getStatus())) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();
        return Result.success(employeeLoginVO);
    }


    /**
     * 员工分页查询
     *
     * @param empDTO
     * @return
     */
    @Override
    public Result selectEmpbyPage(EmployeePageQueryDTO empDTO) {
        Page<Object> page = PageHelper.startPage(empDTO.getPage(), empDTO.getPageSize());
        List<Employee> dtos = employeeMapper.selectEmpbyPage(empDTO);
        PageResult pageVO = new PageResult<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setRecords(dtos);
        return Result.success(pageVO);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public EmployeeDTO getById(Long id) {
        EmployeeDTO emp = employeeMapper.getById(id);
        return emp;
    }



    /**
     * 新增员工
     * @param empParam
     * @return
     */
    @Override
    public Employee insert(EemInsertParam empParam) {
        Employee emp = new Employee();
        emp.setPassword("e10adc3949ba59abbe56e057f20f883e");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        //获取当前操作人id
        String id = getOperatorId.getId();
        emp.setCreateUser(Long.valueOf(id));
        emp.setUpdateUser(Long.valueOf(id));
        //封装参数数据
        emp.setIdNumber(empParam.getIdNumber());
        emp.setName(empParam.getName());
        emp.setPhone(empParam.getPhone());
        emp.setSex(empParam.getSex());
        emp.setUsername(empParam.getUsername());
        employeeMapper.insert(emp);
        return null;
    }



    @Override
    public int status(Integer status, Long id) {
        int update = employeeMapper.statusUpdate(status, id);
        return update;
    }

    @Override
    public int update(EemInsertParam param) {
        Employee emp = employeeMapper.selectEmpById(param.getId());
        emp.setUpdateTime(LocalDateTime.now());
        //获取当前操作人id
        String id = getOperatorId.getId();
        emp.setUpdateUser(Long.valueOf(id));
        //封装参数数据
        emp.setIdNumber(param.getIdNumber());
        emp.setName(param.getName());
        emp.setPhone(param.getPhone());
        emp.setSex(param.getSex());
        emp.setUsername(param.getUsername());
        int update = employeeMapper.update(emp);
        return update;
    }


}
